// app.js
import request from './utils/request'

App({
  onLaunch() {
    this.getOpenId()
  },
  globalData: {
    userInfo: null,
    isAdmin: false,
  },
  getOpenId(){
    let code2session = wx.getStorageSync('code2session')
    if (code2session) {
      let token = wx.getStorageSync('token')
      if (!token) {
        const para = {
            openid: code2session.openid
          }
          request('/admin/openidLogin', para, 'POST').then((res) => {
            let token = res.tokenHead + res.token
            wx.setStorageSync('token', token)
          })
      }else{
        this.globalData.isAdmin = true;
      }
    } else {
      // 登录
      wx.login({
        success: (res) => {
          if (res.code) {
            const para = {
              code: res.code
            }
            request('/common/miniLogin', para, 'POST').then((res) => {
              wx.setStorageSync('code2session', res)
              const para = {
                openid: res.openid
              }
              request('/admin/openidLogin', para, 'POST').then((res) => {
                let token = res.tokenHead + res.token
                this.App.isAdmin = true;
                wx.setStorageSync('token', token)
              })
            })
          } else {
            wx.showToast({
              title: '登录失败'
            })
          }
        }
      })
    }
  },
})
